<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  " http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps JavaScript API Example</title>

    <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script>
    <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/engine.js'></script>
    <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/GeocoderService.js'></script>
    <script type='text/javascript' src='<%=request.getContextPath()%>/js/prototype.js'></script>

    <script src=" http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAANj-zMTPLea-APQQKgAopOBQ_ANElXRJGoUEtXINHpGstju1viRRsLcyNMc2mFA5GU_yB3iW2tdHOeA"
      type="text/javascript"></script>
    <script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
    <script type="text/javascript">
    //<![CDATA[

     var GeocodingLocationMarkerFactory = Class.create({
       createTransient: function(aLocation) {
         var locationMarker = new TransientGeocodingLocationMarker(aLocation);

         GEvent.addListener(
           locationMarker.marker,
           "dragstart",
           function() {
           locationMarker.marker.closeInfoWindow();
//             locationMarker.closeInfoWindow();
//             locationMarker.clearLocation();
           }
         );
         GEvent.addListener(
           locationMarker.marker,
           "dragend",
           function() {
             locationMarker.marker.bindInfoWindowHtml("Loading...");
             locationMarker.marker.openInfoWindow("Loading");
             GeocoderService.geocodeReverse(
               locationMarker.latitude(),
               locationMarker.longitude(),
               function(aLocation) {
                 locationMarker.updateLocation(aLocation);
               }
             );
           }
         );

         locationMarker.marker.bindInfoWindowHtml(locationMarker.getInfoWindowHtml());

//         locationMarker.updateLocation(aLocation);
         return locationMarker;
       }
     });
     var TransientGeocodingLocationMarker = Class.create({
       initialize: function(aLocation) {
         this.location = aLocation;
         this.marker = new GMarker(
           new GLatLng(
             aLocation.latitude,
             aLocation.longitude
           ),
           {
             icon: new GIcon(G_DEFAULT_ICON, '<%= request.getContextPath() + "/images/marker-yellow.png" %>'),
             draggable: true,
             bouncy: true
           }
         );
       },
//       clearLocation: function() {
//         this.location = null;
//       },
       updateLocation: function(aLocation) {
         this.location = aLocation;
         this.marker.bindInfoWindowHtml(this.getInfoWindowHtml());
         this.showInfoWindow();
       },
       getInfoWindowHtml: function() {
         return "<form id='saveForm' action='<%=request.getContextPath()%>/baches/save.do' method='get'> Lat: <input type='text' name='lat' value='" + this.latitude() + "'><br>" +
          "longitude: <input type='text' name='lng' value='" + this.longitude() + "'/><br>" +
          "calle: " + this.location.streetName + "<br>" +
          "number " + this.location.streetNumber + "<br>"+
          "<a href='javascript:void(0);' onclick='document.getElementById(\"saveForm\").submit();'>Save</a></form>";
       },
       latitude: function() {
         return this.marker.getLatLng().lat();
       },
       longitude: function() {
         return this.marker.getLatLng().lng();
       },
       addToManager: function(manager, level) {
         manager.addMarker(this.marker, level);
       },
       showInfoWindow: function() {
         this.marker.openInfoWindow(this.getInfoWindowHtml());
       },
       closeInfoWindow: function() {
         this.marker.closeInfoWindow();
       }
     });


    var mgr = null;
    var map = null;
    function save(transientMarker) {
      alert(transientMarker);
      var form = document.createElement('saveForm');
      form.lat.value = transientMarker.latitude();
      form.lng.value = transientMarker.longitude();
      form.submit();
    }

    function createMarker(lat, lng) {
      return new GMarker(new GLatLng(lat,lng));
    }

    function createMarkers() {
      var batch = [];
      <c:forEach items="${baches}" var="bache">
          batch.push(
            createMarker(
              <c:out value="${bache.latitud}"/>,
              <c:out value="${bache.longitud}"/>
            )
          );
      </c:forEach>

      return batch;
    }

    function setupMarkers() {
      mgr = new MarkerManager(map);
      mgr.addMarkers(createMarkers(), 11);

      mgr.refresh();
    }

    function loadMap() {
      if (GBrowserIsCompatible()) {
        map = new GMap2( document.getElementById("map"), {mapTypes: [G_SATELLITE_MAP]});
        map.addControl(new GLargeMapControl());
        map.enableScrollWheelZoom();
        map.setCenter(new GLatLng(-34.594936719911, -58.400204257075 ),17);
        window.setTimeout(setupMarkers, 0);
      }
    }

    function unloadMap() {
        GUnload();
    }

    function newMarkerCallback(geocodingResult) {
      if (geocodingResult.uniquelyDeterminedLocation) {
        var location = geocodingResult.locations[0];
        var latitude = location.latitude;
        var longitude = location.longitude;
        var locationMarker = new GeocodingLocationMarkerFactory().createTransient(location);
        locationMarker.addToManager(mgr, 11);
        mgr.refresh();
        //TODO: Centrar el mapa en la posicion del marker.
        locationMarker.showInfoWindow();
      }
    }

    function locate() {
      var calle = document.getElementById("calle").value;
      var altura = document.getElementById("altura").value;
      GeocoderService.geocodeByAddress(
        calle,
        altura,
        newMarkerCallback
      );
    }
    //]]>
    </script>
  </head>
  <body onload="loadMap()" onunload="unloadMap()">
    <div id="map" style="width: 500px; height: 300px"></div>
    <input type="text" id="calle" name="calle"/>
    <input type="text" id="altura" name="altura"/>
    <input type="button" name="locate" onclick="locate()"/>
  </body>
</html>
